package com.ch.clinking.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.Dao.RememberPasswordDao;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.bean.Merchandise;
import com.ch.clinking.bean.RememberPassword;
import com.ch.clinking.bean.Shop;
import com.ch.clinking.bean.User;
import com.google.gson.Gson;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class LoginActivity extends AppCompatActivity {


    private Button loginButton;
    private EditText loginAccount,loginPassword;
    private CheckBox loginRemember,loginAutoLogin;
    private TextView toRegisterShop,toRegister;
    private RememberPasswordDao rememberPasswordDao;
    private ActivityResultLauncher<Intent> requestDataLauncher;
    private ClinkingApplication app;
    private final Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 设置状态栏图标为深色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        //获取注册页面回传来的账号密码----------1
//        requestDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
//            if (result.getResultCode() == RESULT_OK) {
//                assert result.getData() != null;
//                Bundle bundle = result.getData().getExtras();
//                String account = bundle.getString("account","");
//                String password = bundle.getString("password", "");
//
//                loginAccount.setText(account);
//                loginPassword.setText(password);
//            }
//
//        });

        initWidget(); //获取控件ID

        initDate(); //记住密码的数据处理

        initEvent();




    }

    private void initDate() {

        app = ClinkingApplication.getInstance();
        rememberPasswordDao = ClinkingApplication.getInstance().getDatabase().rememberPasswordDao();


        RememberPassword latestUser = rememberPasswordDao.selectLatestUser();
        if (latestUser != null) {
            if (latestUser.isRemember()) {
                loginAccount.setText(latestUser.getAccount());
                loginPassword.setText(latestUser.getPassword());
                loginRemember.setChecked(true);
                if (latestUser.isAuto()) {
                    // 检查用户是否已经登录
                    SharedPreferences preferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
                    boolean isLoggedIn = preferences.getBoolean("is_logged_in", false);
                    loginAutoLogin.setChecked(true);
                    if (isLoggedIn) {
                        if (app.firstLogin) {
                            loginToMain();
                        }
                    }

                }
            } else {
                loginAccount.setText(latestUser.getAccount());
            }
        }

        // 数据加载完成，发送广播
        Intent intent = new Intent("com.example.DATA_LOADED");
        LocalBroadcastManager.getInstance(LoginActivity.this).sendBroadcast(intent);

    }

    private void initEvent() {

        loginAccount.setOnFocusChangeListener((v, hasFocus) -> {
            //失去焦点
            if(!hasFocus){
                String account = loginAccount.getText().toString();
                RememberPassword rememberPassword = rememberPasswordDao.selectByAccount(account);
                if (rememberPassword != null) {
                    loginPassword.setText(rememberPassword.getPassword());
                    loginRemember.setChecked(true);
                } else {
                    loginPassword.setText("");
                    loginRemember.setChecked(false);
                }
            }
        });

        //登录按钮
        loginButton.setOnClickListener(view -> loginToMain());

//        toRegisterShop.setOnClickListener(view -> {
//            Intent intent = new Intent(LoginActivity.this, ShopRegisterActivity.class);
//            requestDataLauncher.launch(intent); //这里跳转页面毕业ststartActivity是因为要接收注册页面回传的数据，这里的方法与--注释1--对应，相当于在注释1创建，在这里使用
//        });
//
//        toRegister.setOnClickListener(view -> {
//            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
//            requestDataLauncher.launch(intent); //这里跳转页面毕业ststartActivity是因为要接收注册页面回传的数据，这里的方法与--注释1--对应，相当于在注释1创建，在这里使用
//        });

    }

    private void loginToMain() {
        String account = loginAccount.getText().toString();
        String password = loginPassword.getText().toString();

        if (TextUtils.isEmpty(account)) {
            Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        //校验账号
        HashMap<String, String> selectUser = new HashMap<>();
        selectUser.put("account",account);
        OkHttpUtil.getInstance().doPostForm("/user/selectByAccount", new DoCallBack() {
            @Override
            public void onSuccess(String result) {

                Log.d("tag", result);
                User user = new Gson().fromJson(result, User.class);
                if (user != null) {
                    Log.d("tag", String.valueOf(user));

                    //校验密码
                    if (TextUtils.equals(password, user.getPassword())) {

                        //App全局User变量
                        app.user = user;

                        rememberPasswordDao.deleteByAccount(account);
                        RememberPassword rememberPassword = new RememberPassword();
                        rememberPassword.setAccount(account);
                        rememberPassword.setPassword(password);
                        rememberPassword.setRemember(loginRemember.isChecked());
                        rememberPassword.setAuto(loginAutoLogin.isChecked());
                        rememberPasswordDao.insert(rememberPassword);

                        // 查询管理的店铺列表
                        HashMap<String, String> selectShopList = new HashMap<>();
                        selectShopList.put("account",user.getAccount());
                        OkHttpUtil.getInstance().doPostForm("/shop/selectShopListByUserId", new DoCallBack() {
                            @Override
                            public void onSuccess(String result) {

                                // 保存登录状态
                                SharedPreferences preferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
                                @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = preferences.edit();
                                editor.putBoolean("is_logged_in", true);
                                editor.apply();

                                Shop[] shopList = new Gson().fromJson(result, Shop[].class);
                                app.shopList = Arrays.asList(shopList);
                                Log.d("getShopId", String.valueOf(app.shopList));
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                LoginActivity.this.finish();
                            }

                            @Override
                            public void onError(Exception e) {
                                Log.d("tag", "shop==null----error");
                                Toast.makeText(LoginActivity.this, "网络错误,获取小队信息失败,请稍后再试", Toast.LENGTH_SHORT).show();
                                handler.postDelayed(LoginActivity.this::finish, 3000);
                            }
                        },selectShopList);
//                        //查询小队
//                        HashMap<String, String> selectShop = new HashMap<>();
//                        selectShop.put("shopId",user.getShopId());
//                        OkHttpUtil.getInstance().doPostForm("/shop/selectById", new DoCallBack() {
//                            @Override
//                            public void onSuccess(String result) {
//                                Shop[] shopList = new Gson().fromJson(result, Shop[].class);
//                                app.shopList = Arrays.asList(shopList);
//                                Log.d("tag login", result);
//                                //App全局Shop变量
////                                app.shop = new Gson().fromJson(result, Shop.class);
//
////                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
//
//                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                                startActivity(intent);
//                                LoginActivity.this.finish();
//                            }
//
//                            @Override
//                            public void onError(Exception e) {
//                                Log.d("tag", "shop==null----error");
//                                Toast.makeText(LoginActivity.this, "网络错误,获取小队信息失败,请稍后再试", Toast.LENGTH_SHORT).show();
//                                handler.postDelayed(LoginActivity.this::finish, 3000);
//                            }
//                        },selectShop);

                    } else {
                        Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(LoginActivity.this, "该账号未注册", Toast.LENGTH_SHORT).show();
                    Log.d("tag", "user==null----success");
                }
            }

            @Override
            public void onError(Exception e) {
                Log.d("tag", "user==null----error");
                Toast.makeText(LoginActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
//                handler.postDelayed(LoginActivity.this::finish, 3000);
            }
        },selectUser);
    }

    private void initWidget() {
        loginButton = findViewById(R.id.loginButton);
        loginAccount = findViewById(R.id.loginEditAccount);
        loginPassword = findViewById(R.id.loginEditPassword);
        loginRemember = findViewById(R.id.loginRemember);
        loginAutoLogin = findViewById(R.id.loginAutoLogin);
//        agreement = findViewById(R.id.agreement);
        toRegisterShop = findViewById(R.id.toRegisterShop);
        toRegister = findViewById(R.id.toRegister);
    }
}